package com.wcj.common.dao.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;

import com.wcj.common.dao.WcjDao;
import com.wcj.common.utils.ReflectionUtils;

public class WcjDaoImpl<T extends Serializable> extends WcjHibernateDao implements WcjDao<T>{
	
	protected Class<T> entityClass;
	
	public WcjDaoImpl(){
		this.entityClass =  ReflectionUtils.getSuperClassGenricType(getClass());
	}
	
	@Override
	public T get( Serializable id ) {
		return this.getHibernateTemplate().get( entityClass, id );
	}
	
	@Override
	public T load(Serializable id) {
		return this.getHibernateTemplate().load(entityClass, id);
	}
	
	@Override
	public void save( T entity ) {
		this.getHibernateTemplate().save(entity);
	}
	
	@Override
	public void saveAll( Collection<T> entitys ) {
		this.getHibernateTemplate().saveOrUpdateAll( entitys );
	}
	
	@Override
	public void saveOrUpdate( T entity ) {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}
	
	@Override
	public List<T> findByCriteria( DetachedCriteria criteria  ) {
		return this.getHibernateTemplate().findByCriteria(criteria);
	}
	
	@Override
	public void deleteObj(T entity) {
		this.getHibernateTemplate().delete(entity);
	}

	@Override
	public void deleteObjById( Serializable id ) {
		this.getHibernateTemplate().delete( this.load(id) );
	}

	@Override
	public void deleteObjByIds( Serializable[] ids ) {
		for( Serializable id : ids ){
			deleteObjById( id );
		}
	}
	
	public void deleteDataBySql( String queryString ){
		this.getHibernateTemplate().bulkUpdate(queryString);
	}
	
	public void deleteDataBySql( String queryString , Object...params ){
		this.getHibernateTemplate().bulkUpdate(queryString,params);
	}
	
	@Override
	public T findUniqueObj(String name, Object value) {
		return (T) genericFindUniqueBy(entityClass, name, value);
	}

	@Override
	public List<T> loadAll() {
		return this.getHibernateTemplate().loadAll(entityClass);
	}

	@Override
	public List<T> findAll() {
		DetachedCriteria criteria  = DetachedCriteria.forClass( entityClass );
		return this.getHibernateTemplate().findByCriteria( criteria );
	}

	@Override
	public List<T> findByLike(String name, String value) {
		return genericFindByLike(entityClass, name, value);
	}

	@Override
	public boolean isNotUnique(T entity, String names) {
		return super.isGenericNotUnique(entityClass, entity, names);
	}
	
}
